package BIO.udp;
/*
 * @Author  Wrial
 * @Date Created in 22:18 2020/4/9
 * @Description 发送端
 */

import java.io.FileInputStream;
import java.io.IOException;
import java.net.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import java.nio.channels.Channel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class UDPClient {


    public static void main(String[] args) throws IOException, InterruptedException {

        UDPClient udpClient = new UDPClient();
        for (int i = 0; i < 5; i++) {

            DatagramPacket msg = udpClient.transferMsgToPacket("127.0.0.1", "hello server", 8090);
            udpClient.sendMessage(msg);
            Thread.sleep(100);
        }
    }

    private DatagramSocket datagramSocket;

    public UDPClient() throws SocketException {
        datagramSocket = new DatagramSocket();
        System.out.println("init datagramSocket");
    }

    public void sendMessage(DatagramPacket datagramPacket) throws IOException {
        datagramSocket.send(datagramPacket);
        System.out.println("Message send  success ---" + new String(datagramPacket.getData()));
    }

    public DatagramPacket transferMsgToPacket(String addr, String msg, int port) throws UnknownHostException {
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0,
                msg.length(), InetAddress.getByName(addr), port);
        return packet;
    }


}
